{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['finetune-t5-tiny-standard-bahasa-cased/checkpoint-1760000',\n",
       " 'finetune-t5-tiny-standard-bahasa-cased/checkpoint-1770000',\n",
       " 'finetune-t5-tiny-standard-bahasa-cased/checkpoint-1780000']"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from glob import glob\n",
    "\n",
    "checkpoints = sorted(glob('finetune-t5-tiny-standard-bahasa-cased/checkpoint-*'))\n",
    "checkpoints"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import T5Tokenizer, T5ForConditionalGeneration\n",
    "\n",
    "tokenizer = T5Tokenizer.from_pretrained('mesolitica/t5-small-standard-bahasa-cased')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = T5ForConditionalGeneration.from_pretrained(checkpoints[-1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = \"Kabinet bersetuju mewujudkan satu jawatan kuasa dalaman untuk menyiasat isu 'perbalahan' antara Jabatan Perkhidmatan Awam (JPA) dan Kesatuan Perkhidmatan Imigresen Semenanjung Malaysia (KPISM)\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_ids = tokenizer.encode(f'parafrasa: {s}', return_tensors = 'pt')\n",
    "outputs = model.generate(input_ids, do_sample=True,\n",
    "    max_length=256,\n",
    "    top_k=50,\n",
    "    top_p=0.95,\n",
    "    early_stopping=True,\n",
    "    num_return_sequences=5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[\"Kabinet bersetuju mewujudkan satu jawatan kuasa dalaman untuk menyiasat isu 'perbalahan antara Jabatan Perkhidmatan Awam (JPA) dan Kesatuan Perkhidmatan Imigresen Semenanjung Malaysia (KPISM).\",\n",
       " 'Kabinet bersetuju mewujudkan satu jawatan kuasa dalaman untuk menyiasat isu \"perbalahan\" antara Jabatan Perkhidmatan Awam (JPA) dan Kesatuan Perkhidmatan Imigresen Semenanjung Malaysia (KPISM).',\n",
       " \"Kabinet bersetuju mewujudkan satu jawatan kuasa dalaman untuk menyiasat isu 'perbalahan' antara Jabatan Perkhidmatan Awam (JPA) dan Kesatuan Perkhidmatan Imigresen Semenanjung Malaysia (KPISM).\",\n",
       " 'Kabinet bersetuju mewujudkan satu jawatan kuasa dalaman untuk menyiasat isu-isu di kalangan Jabatan Perkhidmatan Awam (JPA) dan Kesatuan Perkhidmatan Imigresen Semenanjung Malaysia (KPISM).',\n",
       " 'Kabinet bersetuju mewujudkan satu jawatan kuasa dalaman untuk menyiasat isu \"perbalahan\" antara Jabatan Perkhidmatan Awam (JPA) dan Kesatuan Perkhidmatan Imigresen Semenanjung Malaysia (KPISM).']"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tokenizer.batch_decode(outputs, skip_special_tokens = True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/ubuntu/.local/lib/python3.8/site-packages/huggingface_hub/utils/_deprecation.py:38: FutureWarning: Deprecated positional argument(s) used in 'create_repo': pass token='finetune-paraphrase-t5-tiny-standard-bahasa-cased' as keyword args. From version 0.12 passing these as positional arguments will result in an error,\n",
      "  warnings.warn(\n",
      "/home/ubuntu/.local/lib/python3.8/site-packages/huggingface_hub/hf_api.py:102: FutureWarning: `name` and `organization` input arguments are deprecated and will be removed in v0.10. Pass `repo_id` instead.\n",
      "  warnings.warn(\n",
      "/home/ubuntu/.local/lib/python3.8/site-packages/huggingface_hub/hf_api.py:681: FutureWarning: `create_repo` now takes `token` as an optional positional argument. Be sure to adapt your code!\n",
      "  warnings.warn(\n",
      "Cloning https://huggingface.co/mesolitica/finetune-paraphrase-t5-tiny-standard-bahasa-cased into local empty directory.\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "614389ecb78c4281bc29893aaa5581e0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Download file pytorch_model.bin:   0%|          | 8.00k/133M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c48daf8bafdf425aa6703773194a26cf",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Download file spiece.model:   2%|1         | 15.4k/784k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "dea13505651546eda18b5ff3f640d4bc",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Clean file spiece.model:   0%|          | 1.00k/784k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "33c1594a523948d0b302e25760a7cba7",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Clean file pytorch_model.bin:   0%|          | 1.00k/133M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "285b3b966fc3457ba51449b573ba449f",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Upload file pytorch_model.bin:   0%|          | 4.00k/133M [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "remote: Scanning LFS files for validity, may be slow...        \n",
      "remote: LFS file scan complete.        \n",
      "To https://huggingface.co/mesolitica/finetune-paraphrase-t5-tiny-standard-bahasa-cased\n",
      "   9f0f5a5..b447613  main -> main\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'https://huggingface.co/mesolitica/finetune-paraphrase-t5-tiny-standard-bahasa-cased/commit/b4476131a296bc1f24e2ae26e9a577406f9ad10c'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.push_to_hub('finetune-paraphrase-t5-tiny-standard-bahasa-cased', organization='mesolitica')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "tokenizer.push_to_hub('finetune-paraphrase-t5-tiny-standard-bahasa-cased', organization='mesolitica')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sacrebleu.metrics import BLEU, CHRF, TER\n",
    "\n",
    "bleu = BLEU()\n",
    "chrf = CHRF(word_order = 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "test = []\n",
    "with open('shuffled-test.json') as fopen:\n",
    "    for l in fopen:\n",
    "        test.append(json.loads(l))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5544"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Antara aplikasi bagi sistem atom sejuk yang terperangkap sedemikian ialah simulasi kuantum sistem jirim berkondensasi Banyak Parti dalam potensi berkala.'"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test[0]['translation']['src']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|████████████████████████████████████████████████████████████████████████████████████████████| 5544/5544 [10:43<00:00,  8.62it/s]\n"
     ]
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "\n",
    "batch_size = 1\n",
    "\n",
    "results = []\n",
    "for i in tqdm(range(0, len(test), batch_size)):\n",
    "    input_ids = [{'input_ids': tokenizer.encode(f\"parafrasa: {s['translation']['src']}\", return_tensors = 'pt')[0]} for s in test[i:i + batch_size]]\n",
    "    padded = tokenizer.pad(input_ids, padding = 'longest')\n",
    "    outputs = model.generate(**padded, max_length = 1000)\n",
    "    for o in outputs:\n",
    "        results.append(tokenizer.decode(o, skip_special_tokens=True))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "filtered_left, filtered_right = [], []\n",
    "for no, r in enumerate(results):\n",
    "    if len(r):\n",
    "        filtered_left.append(r)\n",
    "        filtered_right.append(test[no]['translation']['tgt'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'BLEU',\n",
       " 'score': 36.92696648298233,\n",
       " '_mean': -1.0,\n",
       " '_ci': -1.0,\n",
       " '_verbose': '62.5/42.3/33.0/26.9 (BP = 0.943 ratio = 0.945 hyp_len = 95496 ref_len = 101064)',\n",
       " 'bp': 0.9433611337299734,\n",
       " 'counts': [59650, 38055, 27875, 21217],\n",
       " 'totals': [95496, 89952, 84408, 78864],\n",
       " 'sys_len': 95496,\n",
       " 'ref_len': 101064,\n",
       " 'precisions': [62.46334925023038,\n",
       "  42.30589647812167,\n",
       "  33.02412093640413,\n",
       "  26.90327652667884],\n",
       " 'prec_str': '62.5/42.3/33.0/26.9',\n",
       " 'ratio': 0.944906198052719}"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "refs = [filtered_right]\n",
    "sys = filtered_left\n",
    "r = bleu.corpus_score(sys, refs)\n",
    "r.__dict__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
